package media

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) checkCloseTransportReqData(data common.CloseTransportReqData) error {
	// Check if router ID is provided
	if data.RouterId == "" {
		return errors.New("router ID is required in close transport request")
	}

	// Check if transport ID is provided
	if data.TransportId == "" {
		return errors.New("transport ID is required in close transport request")
	}

	// Check if the transport exists
	if !s.TransportExists(data.RouterId, data.TransportId) {
		return errors.New("transport does not exist")
	}

	return nil
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) sendCloseTransportResponse(rid string, code int, msg string,
	data common.CloseTransportReqData) {
	resData := common.ResMsgData{
		Code: code,
		Msg:  msg,
		Data: common.CloseTransportResData{
			RouterId:    data.RouterId,
			TransportId: data.TransportId,
		},
	}
	resMsg := common.Message{
		Cmd:  common.CLOSE_TRANSPORT_RES,
		Rid:  rid,
		Data: resData,
	}

	if err := s.wsClient.Send(resMsg); err != nil {
		LOG().WithError(err).Error("Failed to send close transport response")
	}
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) handleCloseTransportReq(msg common.Message) error {
	var reqData common.CloseTransportReqData
	if err := mapstructure.Decode(msg.Data, &reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to decode close transport request data")
		return nil
	}

	// Validate request data
	if err := s.checkCloseTransportReqData(reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("invalid close transport request data")
		s.sendCloseTransportResponse(msg.Rid, 1, err.Error(), reqData)
		return nil
	}

	// Close the transport
	if err := s.CloseTransport(reqData.RouterId, reqData.TransportId); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to close transport")
		s.sendCloseTransportResponse(msg.Rid, 1, "failed to close transport: "+err.Error(), reqData)
		return nil
	}

	// Send response
	s.sendCloseTransportResponse(msg.Rid, 0, "Transport closed successfully", reqData)

	return nil
}
